package com.ruoyi.common.core.config;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.Data;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author xsj
 * @create 2023-11-11 14:32
 */
@Configuration
@Data
public class OssConfig {

    public static String endPoint="oss-cn-hangzhou.aliyuncs.com";
    public static String accessKeyId="LTAI5tALCb3EqEEGTGvgf8g6";
    public static String accessKeySecret="ABio7e4DO1WZTkaY7YBpnKKZ1pcwmV";
    public static String bucketName="youban-dev";
    public static String serverUrl="https://static.youbantech.com/app/";
    private OSS aliOss;


    public String uploadFile(MultipartFile file) {
        try {
            //创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            //上传文件流
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //获取文件后缀
            String extendName = fileName.substring(fileName.lastIndexOf("."));
            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid+extendName;
            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //2023/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy-MM-dd");
            fileName = timeUrl+"/"+fileName;
            //调用方法实现上传
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, "app/"+fileName, inputStream);
            //关闭OSSClient。
            ossClient.shutdown();
            //上传之后文件路径
            //https://yygh-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            //返回
            return serverUrl+fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
